Ext.namespace("Selector");

/*
 * @p {object} 父窗体实例, 必须有setUsers(o)方法
 * @t {String} label & title
 * */
Selector.User = function(p,t,isSign,rowIndex) {
	this.parentPanel = p;
	this.rowIndex=rowIndex;
	this.loadMask = null;
	this.loader = new Ext.tree.TreeLoader({
        url: '../branch/subBranch.form?snaptime=' + Date.parse(new Date())
    });
	this.root = new Ext.tree.TreeNode({
		id: 0,
		text: '上海移动',
		iconCls: 'icon-group',
		expanded: true
	});
	this.branch = new Ext.tree.TreePanel({
        animate: false,
        autoScroll:true,
        loader: this.loader,
        root: this.root,
        rootVisible: false,
        containerScroll: true,
        height: 250,
        width: 250
    });
	this.userFields = ['id', 'name'];
	this.userRecord = Ext.data.Record.create(this.userFields);
    this.userStore = new Ext.data.JsonStore({
        fields: this.userFields
    });
	this.userList = new Ext.ux.form.SuperBoxSelect({
        fieldLabel: t,
        resizable: true,
        width: 170,
        store: this.userStore,
        mode: 'local',
        displayField: 'name',
        valueField: 'id',
        allowBlank: false,
        blankText: '请选择' + t + '!',
		forceSelection : true
     });
	
	this.form = new Ext.FormPanel({
        bodyStyle: 'padding: 5px 5px 0',
        labelWidth: 55,
        labelAlign: 'right',
        width: 268,
        items: [this.userList, this.branch]
    });
	
	Selector.User.superclass.constructor.call(this, {
		title: t,
        bodyStyle: 'padding: 5px 5px 0',
        autoHeight: true,
        width: 298,
        resizable: false,
        plain: true,
        modal: true,
        autoScroll: true,
        closeAction: 'hide',
        items: [this.form],
        buttons: [{
            text: '确定',
            cls: 'x-btn-text-icon btn-accept',
            handler: this.addUser,
            scope: this
        }, {
            text: '取消',
            cls: 'x-btn-text-icon btn-cancel',
            handler: this.hide.createDelegate(this, [])
        }]
	});
	
	this.loader.on("beforeload", function(treeLoader, node) {
		treeLoader.baseParams.branchId = node.id;
    }, this);
	this.loader.on("load", this.loadBranch, this);
	this.branch.getSelectionModel().on('selectionchange', this.nodeChange, this);
	
	this.connUser = new Ext.data.Connection({
		url: '../branch/users.form?timesnap=' + Date.parse(new Date()),
		method: 'POST'
	});
	this.connBranch = new Ext.data.Connection({
		url: '../branch/branch.form?timesnap=' + Date.parse(new Date()),
		method: 'POST'
	});
};
Ext.extend(Selector.User, Ext.Window, {
	addUser: function(btn, event) {
		if (!this.userList.isValid()) return;
		if(this.rowIndex >=0){
			this.parentPanel.setUsers(this.userList.getValueEx(),this.rowIndex);
		}
		else{
			this.parentPanel.setUsers(this.userList.getValueEx());
		}
		this.hide();
	},
	loadUsers: function(id) {
		if (!this.loadMask) {
			 this.loadMask = new Ext.LoadMask(this.form.getEl(), {msg: '获取职员中，请稍候...'});
		}
		this.loadMask.show();
		Utils.request(this.connUser, {
			params: {branchId: id},
			scope: this,
			success: function(resp, action) {
				this.scope.userStore.removeAll();
				if (!resp.success) return;
				var users = resp.users;
				for(var i=0, u; u = users[i++];) {
					this.scope.userStore.add(new this.scope.userRecord(u));
				}
			},
			after: function() {
				if (!this.scope.loadMask) return;
				this.scope.loadMask.hide();
			}
		});
	},
	nodeChange : function(sm, node) {
		if (!node) return;	// if node remove, selection change event will be fired.
		node.expand();
		this.loadUsers(node.id);
	},
	loadBranch: function(treeLoader, node, response) {
		var data = Ext.util.JSON.decode(response.responseText);
		if (!data.success) return;
		var branchs = data.branchs;
		if (!branchs) return;
		var childrens = [];
		for(var i=0, b; b = branchs[i++];) {
			childrens.push({
				id: b.id,
				text: b.name,
				iconCls: 'icon-group'
			});
		}
		node.appendChild(childrens);
	},
	clearBranch: function() {
		Ext.each(this.root.childNodes, function(n, i) {
			n.remove();
		}, this);
	},
	initUsers: function(users) {
//		this.userList.setValueEx(users);
		this.userList.store.loadData(users);
		var userIds = [];
		for(var i=0;i<users.length;i++){
			userIds.push(users[i].id);
		}
		this.userList.setValue(userIds.join(','));
	},
	show: function() {
		this.clearBranch();
		Utils.request(this.connBranch, {
			scope: this,
			success: function(resp, action){
				if (!resp.success) return;
				var branchs = resp.branchs;
				var childrens = [];
				for(var i=0, b; b=branchs[i++];) {
					childrens.push({
						id: b.id,
						text: b.name//,
						//iconCls: 'icon-group'
					});
				}
				this.scope.root.appendChild(childrens);
			}
		});
		Selector.User.superclass.show.apply(this, arguments);
	}
});

